package org.csu.mybigpro.controller;

import jakarta.annotation.Resource;
import org.csu.mybigpro.DTO.TestUpdateDTO;
import org.csu.mybigpro.common.CommonResponse;
import org.csu.mybigpro.domain.Test;
import org.csu.mybigpro.properties.TestProperties;
import org.csu.mybigpro.service.TestService;
import org.csu.mybigpro.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/teacher/test")
public class TestController {
    @Autowired
    private TestService testService;

    @Resource
    private TestProperties testProperties;  // 你定义的配置类，里面有 uploadPath 路径

    @Autowired
    private MinioUtil minioUtil;

    @PostMapping("/publish")
    public CommonResponse<String> publishTest(
            @RequestParam("name") String name,
            @RequestParam("courseId") Long courseId,
            @RequestParam("totalScore") Integer totalScore,
            @RequestParam("timeLimit") Integer timeLimit,
            @RequestParam("createTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime createTime,
            @RequestParam(value = "file", required = false) MultipartFile file
    ) {
        String filePath = null;

        // 如果上传了文件，使用 MinioUtil 上传，并获取可访问的 URL
        if (file != null && !file.isEmpty()) {
            try {
                // uploadFile 方法会返回形如 http://host:port/bucketName/objectName 的访问链接
                filePath = minioUtil.uploadFile(file);
            } catch (Exception e) {
                System.out.println("上传考试文件到 MinIO 失败");
                return CommonResponse.createForError(400, "文件上传失败: " + e.getMessage());
            }
        }

        // 构造 Test 对象并保存
        Test test = new Test();
        test.setName(name);
        test.setCourseId(courseId);
        test.setTotalScore(totalScore);
        test.setTimeLimit(timeLimit);
        test.setCreateTime(createTime);
        test.setFilePath(filePath);

        testService.saveTest(test);

        Map<String, Object> data = new HashMap<>();
        data.put("test", test);

        return CommonResponse.createForSuccess("试卷发布成功", data.toString());
    }

    // ✅ 查询单个
    @GetMapping("/{id}")
    public CommonResponse<Test> getTestPaperById(@PathVariable Long id) {
        return CommonResponse.createForSuccess(testService.getTestById(id));
    }

    // ✅ 查询全部
    @GetMapping("/list")
    public CommonResponse<List<Test>> getAllTestPapers() {
        return CommonResponse.createForSuccess(testService.getAllTests());
    }

    // ✅ 修改
    @PutMapping("/update")
    public CommonResponse<String> updateTestPaper(
            @ModelAttribute TestUpdateDTO dto,
            @RequestParam(value = "file", required = false) MultipartFile file
    ) {
        Test existing = testService.getTestById(dto.getId());
        if (existing == null) {
            return CommonResponse.createForError(404, "试卷不存在");
        }

        if (dto.getName() != null) existing.setName(dto.getName());
        if (dto.getCourseId() != null) existing.setCourseId(dto.getCourseId());
        if (dto.getTotalScore() != null) existing.setTotalScore(dto.getTotalScore());
        if (dto.getTimeLimit() != null) existing.setTimeLimit(dto.getTimeLimit());
        if (dto.getCreateTime() != null) existing.setCreateTime(dto.getCreateTime());

        if (file != null && !file.isEmpty()) {
            try {
                String url = minioUtil.uploadFile(file);
                existing.setFilePath(url);
            } catch (Exception e) {
                return CommonResponse.createForError(500, "文件上传失败：" + e.getMessage());
            }
        }

        testService.updateTest(existing);
        return CommonResponse.createForSuccess("试卷更新成功");
    }

    // ✅ 删除
    @DeleteMapping("/delete/{id}")
    public CommonResponse<String> deleteTestPaper(@PathVariable Long id) {
        testService.deleteTest(id);
        return CommonResponse.createForSuccess("删除成功");
    }

    @GetMapping("/name/{name}")
    public CommonResponse<List<Test>> getTestPapersByName(@PathVariable String name) {
        return CommonResponse.createForSuccess(testService.getTestByName(name));
    }
}
